package com.situ.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.entity.User;

// /*代表拦截所有的请求
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter{
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("LoginFilter.init()");
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LoginFilter.doFilter()");
		// Ctrl+Shift+O
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse)response;
		String uri = httpServletRequest.getRequestURI();
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("uri: " + uri);
		System.out.println("servletPath: " + servletPath);
		// "/js/plugins/layer/skin/layer.css"
		int lastIndex = servletPath.lastIndexOf(".");
		String extension = "";
		if (lastIndex != -1) {
			extension = servletPath.substring(lastIndex);// .css  .js  .png
		}
		
		if ("/user_login.jsp".equals(servletPath) 
				|| "/user".equals(servletPath)
				|| ".css".equals(servletPath)
				|| ".js".equals(servletPath)
				|| ".png".equals(servletPath)) {
			// 不需要验证登录，直接放行
			chain.doFilter(request, response);
		} else {
			HttpSession session = httpServletRequest.getSession();
			User user = (User)session.getAttribute("user");
			if (user == null) {
				// 用户根本没有登录,重定向到登录界面
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/user_login.jsp");
				return;
			}
			// 想让Filter继续往下执行
			chain.doFilter(request, response);
		}
		
		
	}


	@Override
	public void destroy() {
		System.out.println("LoginFilter.destroy()");
	}

	

	
}
